layui.define(['table', 'treeTable', 'tableSelect', 'laydate'], function (exports) {

    var $ = layui.$
        , form = layui.form
        , table = layui.table
        , setter = layui.setter
        , admin = layui.admin
        , tableSelect = layui.tableSelect
        , laydate = layui.laydate
        , treeTable = layui.treeTable;

    var colsArr;
    var tableTitle;//表头标题
    var tableField;//表头标题 有隐藏
    var tableHead;//表头字段
    var tableSearch = {};//全局搜索条件

    var id;
    var goodscode = $('#goodscode', parent.document).val();

    form.verify({
        //我们既支持上述函数式的方式，也支持下述数组的形式
        //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]

        num: [
            /(^$)|^(^[0-9]\d*\.([0-9]{1,})$)|^[0-9]\d*$/
            , '请输入整数或小数'
        ]

    });


    layui.laydate.render({
        elem: '#startdateLayDate' //指定元素
        , trigger: 'click'
    });

    layui.laydate.render({
        elem: '#enddateLayDate' //指定元素
        , trigger: 'click'
    });
    var parentJson = {};
    var obj = {
        setParentJson: function setParentJson(json) {
            parentJson = json;
            load();
        }
    }

    hiddendiv();

    function hiddendiv() {
        $("#table").show();
        $("#form").hide();
        loadtable();
    }

    function showdiv() {
        $("#table").hide();
        $("#form").show();
    }


    $("#price").blur("input propertychange", function (event) {
        //  具体代码
        if ($("#memberprice").val() == '' || $("#memberprice").val() == undefined) {
           var memberdegree = $("#memberdegree option:selected").val();
           $("#memberprice").val(toDecimal($("#price").val(),Number(memberdegree)+1));
           $("#memberdiscount").val("1.00")
        }else {
            $("#memberdiscount").val(toDecimal2(Number($("#memberprice").val()) / Number($("#price").val())))
        }

        if ($("#tradeprice").val() == '' || $("#tradeprice").val() == undefined) {
            var tradedegree = $("#tradedegree option:selected").val();
            $("#tradeprice").val(toDecimal($("#price").val(),Number(tradedegree)+1));
            // $("#").val($("#price").val())
            $("#tradediscount").val("1.00")
        }else {
            $("#tradediscount").val(toDecimal2(Number($("#tradeprice").val()) / Number($("#price").val())))
        }
        if ($("#sendprice").val() != ''&& $("#sendprice").val() == undefined) {
            $("#sendpricediscount").val(toDecimal2(Number($("#sendprice").val()) / Number($("#price").val())))
        }

    });

    $("#memberprice").blur("input propertychange", function (event) {
        //  具体代码
        if ($("#price").val() != '' && $("#price").val() != undefined) {
            $("#memberdiscount").val(toDecimal2(Number($("#memberprice").val()) / Number($("#price").val())))
        }
    });

    $("#tradeprice").blur("input propertychange", function (event) {
        //  具体代码
        if ($("#price").val() != '' && $("#price").val() != undefined) {
            $("#tradediscount").val(toDecimal2(Number($("#tradeprice").val()) / Number($("#price").val())))
        }
    });
    $("#sendprice").blur("input propertychange", function (event) {
        //  具体代码
        if ($("#price").val() != '' && $("#price").val() != undefined) {
            $("#sendpricediscount").val(toDecimal2(Number($("#sendprice").val()) / Number($("#price").val())))
        }
    });


    function toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }



    function loadtable() {
        colsArr = [
            {field: 'goodscode', hide: true, title: '所属系统', sort: false},
            {field: 'system', hide: true, title: '所属系统', sort: false},
            {field: 'systemname', title: '所属系统', width: 100, sort: false},
            {field: 'price', title: '售价', width: 100, sort: false},
            {field: 'groupprice', title: '拼团价', width: 100, sort: false},
            {field: 'markprice', title: '划线价', width: 100, sort: false},
            {field: 'memberprice', title: '会员价', width: 100, sort: false},
            {field: 'memberdiscount', title: '会员折扣率', width: 100, sort: false},
            {field: 'memberdegree', title: '会员价精度', width: 100, sort: false},
            {field: 'tradeprice', title: '批发价', width: 100, sort: false},
            {field: 'tradedegree', title: '批发价精度', width: 100, sort: false},
            {field: 'tradediscount', title: '批发折扣率', width: 100, sort: false},
            {field: 'makeupsendprice', title: '加价配送价', width: 100, sort: false},
            {field: 'inprice', title: '最新进价', width: 100, sort: false},
            {field: 'sendprice', title: '配送价', width: 100, sort: false},
            {field: 'saletaxrate', title: '销项税', width: 100, sort: false},
            {field: 'changeprice', title: '调价控制', width: 100, sort: false},
            {fixed: 'right', title: '操作', width: 70, toolbar: '#opeTable'}
        ];

        layui.each(colsArr, function (inx, val) {
            tableHead += val.hasOwnProperty('field') ? val.field : '-';
            tableHead += ',';
            tableTitle += val.hasOwnProperty('title') ? (val.hide ? '' : val.title + ',') : ',';
            tableField += val.hasOwnProperty('field') ? (val.hide ? '' : val.field + ',') : ',';
        })
        //tableHead是获取表字段
        tableHead = tableHead.substring(tableHead.indexOf(',') + 1, tableHead.length - 1);
        //导出时需要用到标题
        tableTitle = tableTitle.substring(tableTitle.indexOf(',') + 1, tableTitle.length - 1);
        //导出需要用到实际导出的字段
        tableField = tableField.substring(tableField.indexOf(',') + 1, tableField.length - 1);
        tableSearch["goodscode"] = goodscode;
        //用户管理
        table.render({
            elem: '#goods_order_table'
            , url: setter.host + '/goods_order/getSelectSystemPrice'
            , cols: [colsArr]
            //,toolbar: 'true'
            //,defaultToolbar: ['print']
            , method: 'post'
            , contentType: 'application/json; charset=utf-8'
            , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                search: tableSearch //查询字段
                , headField: tableHead //表头字段
            }
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            , height: '640'
            , text: {
                none: '暂无相关数据'
            }
        });
    }

    table.on('row(goods_order_table)', function(obj){
        // var data = obj.data;
        id = obj.data.system;
        var delId = {};
        delId.id = obj.data.system;
        layui.admin.req({
            url: layui.setter.host + '/goods_system_supplier/roleList_dept'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(delId)
            , done: function (res) {
                if (res.data.length == 0) {
                    $("#system").val(obj.data.systemname)
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_system_price/getsystemInfo?id=' + id + '&goodscode=' + goodscode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (res) {
                            showdiv()
                            if (res.status == setter.response.statusCode.status_Success) {
                                if (res.data.id[0] == undefined) {
                                    $("#price").val('');
                                    $("#groupprice").val('');
                                    $("#markprice").val('');
                                    $("#memberprice").val('');
                                    $("#memberdiscount").val('');
                                    $("#tradeprice").val('');
                                    $("#tradediscount").val('');
                                    $("#makeupsendprice").val('');
                                    $("#inprice").val(res.data.inprice[0].inprice);
                                    $("#sendprice").val('');
                                    $("#saletaxrate").val('');
                                } else {
                                    $("#price").val(res.data.id[0].price);
                                    $("#groupprice").val(res.data.id[0].groupprice);
                                    $("#markprice").val(res.data.id[0].markprice);
                                    // $("#memberprice").val(res.data.id[0].memberprice);
                                    $("#memberdegree").val(res.data.id[0].memberdegree);
                                    $("#memberdiscount").val(res.data.id[0].memberdiscount);
                                    // $("#tradeprice").val(res.data.id[0].tradeprice);
                                    $("#memberprice").val(toDecimal(res.data.id[0].memberprice,Number(res.data.id[0].memberdegree)+1));
                                    $("#tradeprice").val(toDecimal(res.data.id[0].tradeprice,Number(res.data.id[0].tradedegree)+1));
                                    $("#tradedegree").val(res.data.id[0].tradedegree);
                                    $("#tradediscount").val(res.data.id[0].tradediscount);
                                    $("#makeupsendprice").val(res.data.id[0].makeupsendprice);
                                    $("#inprice").val(res.data.id[0].inprice);
                                    $("#sendprice").val(res.data.id[0].sendprice);
                                    $("#saletaxrate").val(res.data.id[0].saletaxrate);
                                    $("#changeprice").val(res.data.id[0].changeprice);
                                }

                                form.render();
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                } else {
                    hiddendiv()
                }
            }
        });


        var classcode;
        $("#tableDelete").on("click", function () {
            classcode = obj.data.classcode;
            layer.open({
                content: '是否删除？'
                , btn: ['是', '否']
                , yes: function (index, layero) {
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_class/deleteGoods?classcode=' + classcode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        data: {},
                        dataType: 'json',
                        success: function (res) {
                            //请求成功后
                            if (res.status == setter.response.statusCode.status_Success) {
                                layer.msg(res.msg);
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                }
                , btn3: function (index, layero) {
                    return false;
                }
                , cancel: function () {
                    return false;
                }
            });
        })
        var price;
        var groupprice;
        var markprice;
        var memberprice;
        var memberdegree;
        var memberdiscount;
        var tradeprice;
        var tradedegree;
        var tradediscount;
        var makeupsendprice;
        var inprice;
        var sendprice;
        var saletaxrate;
        var changeprice;


        $("#tableInsert").on("click", function () {

            $("#fatherclassname").attr("readonly", false);
            $("#classcode").attr("readonly", false);
            fatherclassname = $("#classname").val();
            $("#fatherclassname").val($("#classname").val());
            fatherclasscode = $("#classcode").val();
            $("#fatherclasscode").val($("#classcode").val());
            $("#fatherclassname").attr("readonly", true);
            $("#fatherclasscode").attr("readonly", true);
            $("#classcode").val("");
            $("#classname").attr("readonly", false);
            $("#classname").val("");
            $("#classremark").attr("readonly", false);
            $("#classremark").val("");
            dateType = $("#tableInsert").attr("data-type");
        })
        $("#tableEdit").on("click", function () {
            $("#classname").attr("readonly", false);
            $("#classremark").attr("readonly", false);
            dateType = $("#tableEdit").attr("data-type");
        })
    });

    function load() {
        addByFilling();
    }



    function addByFilling() {
        layui.admin.req({
            url: layui.setter.host + '/goods_system_price/fillAdd'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(parentJson)
            , done: function (res) {
                //请求成功后
                if (res.status == 1000) {
                    layer.msg(res.msg);
                } else {
                    //先填充complexselect的下拉框
                    layui.each(res.data.select, function (inx, val) {
                        layui.each(val, function (inxSub, valSub) {
                            $("select[name='" + inx + "']").append('<option value="' + valSub.value1 + '">' + valSub.key1 + '</option>');
                            form.render('select');
                        })
                    });
                    form.val('form1', res.data.field);
                }
            }
        });
    }


//	-------------------------------------------------------------------------------------------
    var roleTable = treeTable.render({
        elem: '#LAY-role-list',
        tree: {
            iconIndex: 1,  // 折叠图标显示在第几列
            idName: 'id'  // 自定义id字段的名称
            , arrowType: 'arrow1' //箭头类型
        },
        parent_key: 'fatherid',
        height: '600',
        cols: colsArr = [
            {field: 'id', title: 'id', hide: true},
            {field: 'name', title: '名称'}
        ],
        method: 'post',
        contentType: "application/json; charset=utf-8",
        url: setter.host + '/unite_platform/goods_system_price/roleList'
    });

    table.on('tool(goods_order_table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确认删除该行么', function (index) {
                // console.log("test")
                data.flag = 1;
                layui.admin.req({
                    url: layui.setter.host + '/goods_order/getSelectSystemPriceDel'
                    , type: 'post'
                    , dataType: 'json'
                    , contentType: "application/json; charset=utf-8"
                    , data: JSON.stringify(data)
                    , done: function (res) {
                        //请求成功后
                        table.reload('goods_order_table');
                    }
                });

                layer.close(index);
            });
        }
    });


    form.on('select(memberdegree)', function (data) {
        var memberprice = $("#memberprice").val();
        if (memberprice!=''&&memberprice!=undefined){
            $("#memberprice").val(toDecimal(memberprice,Number(data.value)+1));
        }
    })


    $("#memberprice").blur("input propertychange", function (event) {
        var memberdegree = $("#memberdegree option:selected").val();
        $("#memberprice").val(toDecimal($("#memberprice").val(),Number(memberdegree)+1));
    });


    form.on('select(tradedegree)', function (data) {
        var tradeprice = $("#tradeprice").val();
        if (tradeprice!=''&&tradeprice!=undefined){
            $("#tradeprice").val(toDecimal(tradeprice,Number(data.value)+1));
        }
    })

    $("#tradeprice").blur("input propertychange", function (event) {
        var tradedegree = $("#tradedegree option:selected").val();
        $("#tradeprice").val(toDecimal($("#tradeprice").val(),Number(tradedegree)+1));
    });


    function toDecimal(x,l) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return false;
        }
        var f = Math.round(x*1000)/1000;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= (rs + l)) {
            s += '0';
        }
        return s;
    }




    treeTable.on('row(LAY-role-list)', function (obj) {
        id = obj.data.id;
        var delId = {};
        delId.id = obj.data.id;
        layui.admin.req({
            url: layui.setter.host + '/goods_system_supplier/roleList_dept'
            , type: 'post'
            , dataType: 'json'
            , contentType: "application/json; charset=utf-8"
            , data: JSON.stringify(delId)
            , done: function (res) {
                if (res.data.length == 0) {
                    $("#system").val(obj.data.name)
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_system_price/getsystemInfo?id=' + id + '&goodscode=' + goodscode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        success: function (res) {
                            showdiv()
                            if (res.status == setter.response.statusCode.status_Success) {
                                if (res.data.id[0] == undefined) {
                                    $("#price").val('');
                                    $("#groupprice").val('');
                                    $("#markprice").val('');
                                    $("#memberprice").val('');
                                    $("#memberdiscount").val('');
                                    $("#tradeprice").val('');
                                    $("#tradediscount").val('');
                                    $("#makeupsendprice").val('');
                                    $("#inprice").val(res.data.inprice[0].inprice);
                                    $("#sendprice").val('');
                                    $("#saletaxrate").val('');
                                } else {
                                    $("#price").val(res.data.id[0].price);
                                    $("#groupprice").val(res.data.id[0].groupprice);
                                    $("#markprice").val(res.data.id[0].markprice);
                                    // $("#memberprice").val(res.data.id[0].memberprice);
                                    $("#memberprice").val(toDecimal(res.data.id[0].memberprice,Number(res.data.id[0].memberdegree)+1));
                                    $("#memberdegree").val(res.data.id[0].memberdegree);
                                    $("#memberdiscount").val(res.data.id[0].memberdiscount);
                                    //toDecimal($("#tradeprice").val(),Number(tradedegree)+1)
                                    // $("#tradeprice").val(res.data.id[0].tradeprice);
                                    $("#tradeprice").val(toDecimal(res.data.id[0].tradeprice,Number(res.data.id[0].tradedegree)+1));
                                    $("#tradedegree").val(res.data.id[0].tradedegree);
                                    $("#tradediscount").val(res.data.id[0].tradediscount);
                                    $("#makeupsendprice").val(res.data.id[0].makeupsendprice);
                                    $("#inprice").val(res.data.id[0].inprice);
                                    $("#sendprice").val(res.data.id[0].sendprice);
                                    $("#saletaxrate").val(res.data.id[0].saletaxrate);
                                    $("#changeprice").val(res.data.id[0].changeprice);
                                }

                                form.render();
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                } else {
                    hiddendiv()
                }
            }
        });


        var classcode;
        $("#tableDelete").on("click", function () {
            classcode = obj.data.classcode;
            layer.open({
                content: '是否删除？'
                , btn: ['是', '否']
                , yes: function (index, layero) {
                    $.ajax({
                        url: setter.host + '/unite_platform/goods_class/deleteGoods?classcode=' + classcode,
                        type: 'get',
                        contentType: "application/json; charset=utf-8",
                        data: {},
                        dataType: 'json',
                        success: function (res) {
                            //请求成功后
                            if (res.status == setter.response.statusCode.status_Success) {
                                layer.msg(res.msg);
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                }
                , btn3: function (index, layero) {
                    return false;
                }
                , cancel: function () {
                    return false;
                }
            });
        })
        var price;
        var groupprice;
        var markprice;
        var memberprice;
        var memberdegree;
        var memberdiscount;
        var tradeprice;
        var tradedegree;
        var tradediscount;
        var makeupsendprice;
        var inprice;
        var sendprice;
        var saletaxrate;
        var changeprice;


        $("#tableInsert").on("click", function () {

            $("#fatherclassname").attr("readonly", false);
            $("#classcode").attr("readonly", false);
            fatherclassname = $("#classname").val();
            $("#fatherclassname").val($("#classname").val());
            fatherclasscode = $("#classcode").val();
            $("#fatherclasscode").val($("#classcode").val());
            $("#fatherclassname").attr("readonly", true);
            $("#fatherclasscode").attr("readonly", true);
            $("#classcode").val("");
            $("#classname").attr("readonly", false);
            $("#classname").val("");
            $("#classremark").attr("readonly", false);
            $("#classremark").val("");
            dateType = $("#tableInsert").attr("data-type");
        })
        $("#tableEdit").on("click", function () {
            $("#classname").attr("readonly", false);
            $("#classremark").attr("readonly", false);
            dateType = $("#tableEdit").attr("data-type");
        })
    });


    var active = {
        backtable: function () {
            hiddendiv();
        },
        save: function () {


            var modifyUrL = layui.setter.host + '/goods_system_price/edit';

            system = id;
            type = $("#type option:selected").val();
            price = $("#price").val();
            memberprice = $("#memberprice").val();
            memberdegree = $("#memberdegree option:selected").val();
            memberdiscount = $("#memberdiscount").val();

            tradeprice = $("#tradeprice").val();
            tradedegree = $("#tradedegree option:selected").val();
            tradediscount = $("#tradediscount").val();

            saletaxrate = $("#saletaxrate").val();
            inprice = $("#inprice").val();

            sendprice = $("#sendprice").val();
            groupprice = $("#groupprice").val();
            sendpricediscount = $("#sendpricediscount").val();
            var json = {
                'goodscode': goodscode,
                'system': id,
                'price': price,
                'type': type,
                'changeprice':0,
                'memberprice': memberprice,
                'memberdegree': memberdegree,
                'memberdiscount': memberdiscount,
                'tradeprice': tradeprice,
                'tradedegree': tradedegree,
                'tradediscount': tradediscount,
                'inprice': inprice,
                'sendprice': sendprice,
                'sendpricediscount': sendpricediscount,
                'saletaxrate': saletaxrate,
                'groupprice': groupprice,
            }

            layui.admin.req({
                url: modifyUrL
                , type: 'post'
                , dataType: 'json'
                , contentType: "application/json; charset=utf-8"
                , data: JSON.stringify(json)
                , success: function (res) {
//						console.log(res);
                    //请求成功后
                    if (res.status == setter.response.statusCode.status_Success) {
                        layer.msg(res.msg);
                    } else {
                        layer.msg(res.msg);
                    }
                }

            });
        }
    }


    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    exports('edit', obj);
});

